<!-- 添加单位 -->
<template>
  <el-dialog :visible.sync="dialogVisible" :before-close="handleCloseBindWarnStandard" :close-on-click-modal="false" :title="title" width="900px" height="300px">
    <el-form v-loading="formLoading" ref="dialogForm" :model="dialogForm" :rules="rules" label-width="120px" class="twoColumn">
      <el-form-item label="单位名称" prop="name">
        <el-input v-model="dialogForm.name" placeholder="请输入单位名称" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="单位简称" prop="abbreviation">
        <el-input v-model="dialogForm.abbreviation" placeholder="请输入单位简称" autocomplete="off"/>
      </el-form-item>
      <div class="img-column">
        <el-form-item label="单位类型" prop="type">
          <el-select v-model="dialogForm.type" placeholder="请选择单位类型">
            <el-option v-for="(key, value) in companyType" :key="key" :label="key" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="地区" prop="province">
          <el-cascader
            :options="options"
            v-model="dialogForm.selectedOptions"
            :props="optionProps"
            size="large"
            filterable
            clearable
            @change="handleChange" />
        </el-form-item>
      </div>
      <el-form-item label="logo" prop="logo" class="img-form-item">
        <img v-if="!uploadSuccess&&dialogForm.logo.length" :src="dialogForm.logo" @click="uploadBtn" >
        <img v-if="uploadSuccess&&!dialogForm.logo.length" :src="plan" @click="uploadBtn">
        <i v-if="!uploadSuccess&&dialogForm.logo.length === 0" :class="uploadClass" @click="uploadBtn" />
        <input id="upload" name="logo" type="file" accept="image/*" @change="upload">
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input v-model="dialogForm.address" placeholder="请输入详细地址" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="联系人姓名" prop="link_user">
        <el-input v-model="dialogForm.link_user" placeholder="请输入联系人姓名" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="联系人手机号" prop="link_user_mobile">
        <el-input v-model="dialogForm.link_user_mobile" placeholder="请输入联系人手机号" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="商务经理" prop="business_manager">
        <el-select v-model="dialogForm.business_manager" placeholder="请选择商务经理">
          <el-option v-for="item in salesmanList" :key="item.uuid" :label="item.nickname" :value="item.uuid" />
        </el-select>
      </el-form-item>
      <el-form-item label="监察方" prop="regulator">
        <el-select v-model="dialogForm.regulator" placeholder="请选择监察方">
          <el-option v-for="item in unitList" :key="item.corp_id" :label="item.name" :value="item.corp_id" />
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="handleCancel">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import $ from 'jquery'
import { companyAdd, companyUpdate } from '@/api/company'
import { validateMobile } from '@/utils/validate'
import { getRegion, unitList, salesmanList } from '@/api/common'

const isMobile = (rule, value, callback) => {
  if (!validateMobile(value)) {
    callback(new Error('请输入正确的手机号码'))
  } else {
    callback()
  }
}
const isProvince = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请选择地区'))
  } else {
    callback()
  }
}
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    dialogForm: {
      type: Object,
      default: () => {
        return {}
      }
    },
    dialogType: {
      type: String,
      default: () => {
        return ''
      }
    }
  },
  data() {
    return {
      uploadSuccess: false,
      uploadClass: 'el-icon-plus avatar-uploader-icon', // el-icon-check
      plan: '',
      title: '',
      options: [],
      optionProps: {
        value: 'area_id',
        label: 'area_name',
        children: 'list'
      },
      selectedOptions: [],
      requestFn: {},
      companyType: this.GLOBAL.companyType,
      // 添加formabbreviation验证
      rules: {
        name: [{
          required: true,
          message: '请输入单位名称',
          trigger: 'change'
        }],
        abbreviation: [{
          required: true,
          message: '请输入单位简称',
          trigger: 'change'
        }],
        type: [{
          required: true,
          message: '请输入单位类型',
          trigger: 'change'
        }],
        province: [{
          required: true,
          message: '请选择地区',
          trigger: 'blur'
        },
        {
          validator: isProvince,
          trigger: 'blur'
        }],
        address: [{
          required: true,
          message: '请输入详细地址',
          trigger: 'change'
        }],
        link_user: [{
          required: true,
          message: '请输入联系人姓名',
          trigger: 'change'
        }],
        link_user_mobile: [{
          required: true,
          message: '请输入联系人手机号',
          trigger: 'change'
        },
        {
          validator: isMobile,
          trigger: 'change'
        }]
      },
      formLoading: false,
      unitList: [],
      salesmanList: []
    }
  },
  watch: {
    dialogType(val) {
      this.init(val)
    },
    dialogVisible(val) {
      if (val) {
        this.uploadSuccess = false
        this.uploadClass = 'el-icon-plus avatar-uploader-icon'
        $('#upload').val('')
      }
    }
  },
  created() {
    this.init(this.dialogType)
    this.getRegion()
    this.getUnitList()
    this.getSalesmanList()
  },
  methods: {
    init(dialogType) {
      if (dialogType === '添加') {
        this.title = '添加单位'
        this.requestFn = companyAdd
      }
      if (dialogType === '修改') {
        this.title = '修改单位'
        this.requestFn = companyUpdate
      }
    },
    handleChange(val) {
      if (val.length > 0) {
        this.dialogForm.province = val[0]
        this.dialogForm.city = val[1]
        this.dialogForm.district = val[2]
      }
    },
    submitForm(val) {
      console.log(JSON.stringify(this.dialogForm))
      this.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          const that = this
          const image = new FormData()
          if (that.dialogForm.logo.length) {
            image.append('logo', '')
          } else {
            image.append('logo', that.dialogForm.logo)
          }
          image.append('abbreviation', that.dialogForm.abbreviation)
          image.append('address', that.dialogForm.address)
          image.append('business_manager', that.dialogForm.business_manager)
          image.append('province', that.dialogForm.province)
          image.append('city', that.dialogForm.city)
          image.append('district', that.dialogForm.district)
          image.append('link_user', that.dialogForm.link_user)
          image.append('link_user_mobile', that.dialogForm.link_user_mobile)
          image.append('name', that.dialogForm.name)
          image.append('regulator', that.dialogForm.regulator)
          image.append('type', that.dialogForm.type)
          if (that.dialogType === '修改') {
            image.append('updated_at', that.dialogForm.updated_at)
            image.append('corp_id', that.dialogForm.corp_id)
            image.append('created_at', that.dialogForm.created_at)
          }
          const params = {
            fileType: 'file',
            data: image
          }
          that.requestFn(params)
            .then((res) => {
              const data = res.data
              if (data.code === 40000) {
                that.$message.success(data.message)
                that.$emit('submitForm', this.dialogForm)
              } else {
                that.$message.warning(data.message)
              }
            })
            .catch((err) => {
              console.log(err)
              that.formLoading = false
            })
        }
      })
    },
    // 新增用户方式切换
    addTypeSwitch(data) {
      this.addType = data
    },
    // 下载模板
    downloadTemplate() {
    },
    // 关闭弹窗
    handleCancel() {
      this.$refs['dialogForm'].resetFields()
      this.$emit('getCancel')
    },
    // 关闭弹窗，不可以删这个方法。不用这个方法点击遮罩层关闭会报错
    handleCloseBindWarnStandard() {
      this.$refs['dialogForm'].resetFields()
      this.$emit('closeBindWarnStandard')
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 点击上传按钮
    uploadBtn(index) {
      $('#upload').click()
    },
    // 上传成功
    upload(e) {
      const isImage = e.target.files[0].type.substr(0, 5) === 'image'
      if (isImage) {
        this.uploadSuccess = true
        this.uploadClass = 'el-icon-check avatar-uploader-icon'
        this.dialogForm.logo = e.target.files[0]
        this.plan = URL.createObjectURL(this.dialogForm.logo)
      } else {
        this.$message.error('请上传图片格式!')
      }
    },
    // 获取省市区
    getRegion() {
      const that = this
      getRegion()
        .then((res) => {
          const data = res.data
          if (data.code === 40000) {
            that.options = data.data
          } else {
            that.$message.warning(data.message)
          }
        })
        .catch((err) => {
          console.log(err)
          that.formLoading = false
        })
    },
    // 获取监管单位
    getUnitList() {
      const that = this
      unitList()
        .then((response) => {
          const data = response.data
          if (data.code === 40000) {
            that.unitList = []
            that.unitList = data.data
            if (that.unitList && that.unitList.length > 0) {
              that.corp_id = that.unitList[0].corp_id
              that.name = that.unitList[0].name
            }
          } else {
            that.$message.warning(data.message)
          }
        })
        .catch((err) => {
          console.log(err)
          that.formLoading = false
        })
    },
    // 获取商务经理
    getSalesmanList() {
      const that = this
      salesmanList()
        .then((response) => {
          if (response.data.code === 40000) {
            that.salesmanList = []
            that.salesmanList = response.data.data
            if (that.salesmanList && that.salesmanList.length > 0) {
              that.uuid = that.salesmanList[0].uuid
              that.nickname = that.salesmanList[0].nickname
            }
          } else {
            that.$message.warning(response.data.message)
          }
        })
        .catch((err) => {
          console.log(err)
          that.formLoading = false
        })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.img-column{
  width: 50%;
  height: 117px;
  float: left;
  .el-form-item{
    width: 100%;
    float: left;
  }
}
.img-form-item{
  margin-bottom: 0px;
  position: relative;
  span{
    position: absolute;
    display: block;
    width: 104px;
    text-align: center;
    left: 0;
    top: 65px;
  }
  img{
    max-width: 100%;
    height: 104px;
    display: block;
    margin-bottom: 14px;
  }
}
#upload {
  display: none;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 104px;
  height: 104px;
  line-height: 104px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader-icon.el-icon-check {
  line-height: 90px;
}
.avatar-uploader-icon:hover{
  border-color: #409EFF;
}
.avatar {
  width: 104px;
  height: 104px;
  display: block;
}
</style>
